package guis.member;

import exceptions.RepositoryException;
import guis.RegisterPanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;

import utils.Date;
import classes.Address;
import classes.Classroom;
import classes.District;
import classes.Gender;
import classes.Member;

import communication.Facade;

public class InsertMemberWindow extends MemberWindow
{
	private static final long	serialVersionUID	= 1032307379765488755L;

	public InsertMemberWindow( JFrame source, RegisterPanel< Member > registerPanel, Facade facade )
	{
		super( "Inserir Novo Membro", "inserir", source, registerPanel, facade );
		createActions();
	}

	private void createActions()
	{
		cancelButton.addActionListener( new ActionListener()
		{

			@Override
			public void actionPerformed( ActionEvent arg0 )
			{
				setVisible( false );
			}

		} );

		actionButton.addActionListener( new ActionListener()
		{

			@Override
			public void actionPerformed( ActionEvent arg0 )
			{
				String name = nameTextField.getText();
				int day = getObjectIntValue( dayComboBox.getSelectedItem() );
				int month = getObjectIntValue( monthComboBox.getSelectedItem() );
				int year = getObjectIntValue( yearComboBox.getSelectedItem() );
				
				Gender gender = null;
				if( maleRadioButton.isSelected() ) 
				{
					gender = Gender.male;
				}
				else if( femaleRadioButton.isSelected() )
				{
					gender = Gender.female;
				}
				
				String phone = phoneTextField.getText();
				String eMail = eMailTextField.getText();
				
				String street = streetTextField.getText();
				String number = numberTextField.getText();
				String cep = cepTextField.getText();
				
				boolean comungant = comungantCheckBox.isSelected();
				
				District district = ( District ) districtComboBox.getSelectedItem();
				int districtId = 0;
				if( district != null ) districtId = district.getId();
				
				Classroom classroom = ( Classroom ) classroomComboBox.getSelectedItem();
				int classroomId = 0;
				if ( classroom != null ) classroomId = classroom.getId();
				
				Address address = new Address( street, number, cep, districtId );

				try
				{
					facade.addAddress( address );
					int addressId = facade.findId( address );
					Member member = new Member( name, gender, new Date( day, month, year ), addressId, phone, eMail, comungant, classroomId );
					
					facade.addMember( member );
					memberPanel.loadTable( null );
					setVisible( false );
				}
				catch ( RepositoryException e )
				{

				}
			}
			
			private int getObjectIntValue( Object object )
			{
				int ret;
				
				if( object != null && object instanceof Integer )
				{
					ret = ( Integer ) object;
				}
				else
				{
					ret = 0;
				}
				
				return ret;
			}

		} );
	}
}
